package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.service.AdLandingPageService;
import com.pig4cloud.pig.api.entity.AdLandingPage;
import com.pig4cloud.pig.api.entity.OrangeLandingPage;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.vo.OrangeLandingPageVo;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ 橙子落地页 前端控制器
 * @author yk
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/orangeLandingPage")
@Api(value = "OrangeLandingPage", tags = "橙子落地页管理模块")
public class OlpController {

	@Autowired
	private final TtAccesstokenService ttAccesstokenService;

	private final AdvService advService;

	private final AdLandingPageService adLandingPageService;

	private String olpId = "page_id";

	/**
	 * 分页查询落地页信息
	 * @return 分页对象
	 */
	@RequestMapping("/getPage")
	public R getPage(OrangeLandingPageVo req, Page<OrangeLandingPage> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if(allList == null || allList.size() == 0) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id",PlatformTypeEnum.TT.getValue());
		queryWrapper.eq("page_type","TT_ORANGE");
		//根据广告主id查询
		String[] advArr = req.getAdvertiserIds();
		if (advArr == null || advArr.length == 0) {
			//查询所有
			queryWrapper.in("advertiser_id", allList);
		} else {
			List<String> selectList = Arrays.asList(advArr);
			if (!allList.containsAll(selectList)) {
				return R.failed("广告账户不可用");
			}
			queryWrapper.in("advertiser_id", selectList);
		}
		//根据落地页名称模糊查询
		if (!StringUtils.isBlank(req.getPageName()) ){
			queryWrapper.like("page_name",req.getPageName());
		}
		//根据落地页id精确查询
		String pageId = req.getPageId();
		if (StringUtils.isNotBlank(pageId)){
			queryWrapper.eq(olpId,pageId);
		}
		//根据落地页id降序
		queryWrapper.orderByDesc(olpId);
		// 分页查询
		IPage<AdLandingPage> iPage = adLandingPageService.getLandingIPage(page, queryWrapper);

		// 重新组装返回对象
		IPage<OrangeLandingPage> resultPage = new Page<>();
		BeanUtils.copyProperties(iPage,resultPage);
		List<OrangeLandingPage> resultList = Lists.newArrayList();
		if (Objects.nonNull(iPage) && CollectionUtils.isNotEmpty(iPage.getRecords())){
			for (AdLandingPage adLandingPage : iPage.getRecords()){
				resultList.add(dealData(adLandingPage));
			}
		}
		resultPage.setRecords(resultList);
		return R.ok(resultPage, "操作成功");
	}

	//获取预览地址
	@RequestMapping("/preview")
	public R previewById(Integer id){
		if (Objects.isNull(id)) {
			return R.failed("id不允许为空");
		}
		AdLandingPage adLandingPage = adLandingPageService.getById(id);
		if (Objects.isNull(adLandingPage)) {
			return R.failed("无此橙子落地页");
		}
		String url = getUrl(adLandingPage);
		return R.ok(url,"操作成功");
	}
	//调用第三方投放平台接口，获取预览地址
	public String getUrl(AdLandingPage adLandingPage) {
		String orangeSitePreviewUrl = "https://ad.oceanengine.com/open_api/2/tools/site/preview/";
		Map<String, Object> data = new HashMap<String, Object>();
		String advertiserId = adLandingPage.getAdvertiserId();
		String pageId = adLandingPage.getPageId();
		data.put("advertiser_id", advertiserId);
		data.put("site_id", pageId);
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		//调第三方平台（头条）接口
		String resultStr = OEHttpUtils.doGet(orangeSitePreviewUrl, data, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		String url = null;
		if (resBean != null && "0".equals(resBean.getCode())) {
			JSONObject jsonObj = resBean.getData();
			url = jsonObj.getString("url");
		}
		if (StringUtils.isBlank(url)){
			url = "https://www.chengzijianzhan.com/tetris/page/" + pageId + "/";
			return url;
		}
		return url;
	}

	//根据id查询:修改时回显
	@RequestMapping("/findById")
	public R getById(Integer id){
		if (Objects.isNull(id)) {
			return R.failed("id不允许为空");
		}
		AdLandingPage adLandingPage = adLandingPageService.getById(id);
		return R.ok(dealData(adLandingPage), "操作成功");
	}

	@RequestMapping("/getSelectPage")
	public R getSelectPage(OrangeLandingPageVo req, Page<OrangeLandingPage> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if (allList == null || allList.isEmpty()) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		//根据广告主id查询
		String advertiserId = req.getAdvertiserId();
		if (StringUtils.isBlank(advertiserId)) {
			return R.failed("未传入广告主id");
		}
		if (!allList.contains(advertiserId)) {
			return R.failed("广告账户不可用");
		}
		queryWrapper.eq("advertiser_id", advertiserId);
		queryWrapper.in("status", "enable", "auditAccepted", "auditDoing");
		//根据落地页名称模糊查询
		if (StringUtils.isNotBlank(req.getPageName())) {
			queryWrapper.like("page_name", req.getPageName());
		}
		//根据落地页id精确查询
		String pageId = req.getPageId();
		if (!StringUtils.isBlank(pageId)){
			queryWrapper.eq(olpId,pageId);
		}
		queryWrapper.orderByDesc(olpId);
		// 分页查询
		IPage<AdLandingPage> iPage = adLandingPageService.getLandingIPage(page, queryWrapper);

		// 重新组装返回对象
		IPage<OrangeLandingPage> resultPage = new Page<>();
		BeanUtils.copyProperties(iPage,resultPage);
		List<OrangeLandingPage> resultList = Lists.newArrayList();
		if (Objects.nonNull(iPage) && CollectionUtils.isNotEmpty(iPage.getRecords())){
			for (AdLandingPage adLandingPage : iPage.getRecords()){
				resultList.add(dealData(adLandingPage));
			}
		}
		resultPage.setRecords(resultList);
		return R.ok(resultPage, "操作成功");
	}

	/**
	 * 20220318 落地页改造统一表，前段不改动 ，后端数据重组
	 * @param adLandingPage
	 * @return
	 */
	private OrangeLandingPage dealData(AdLandingPage adLandingPage){
		if (Objects.nonNull(adLandingPage)) {
			OrangeLandingPage orangeLandingPage = new OrangeLandingPage();
			orangeLandingPage.setId(adLandingPage.getId());
			orangeLandingPage.setPageUrl(adLandingPage.getPageUrl());
			orangeLandingPage.setPageName(adLandingPage.getPageName());
			orangeLandingPage.setPageId(adLandingPage.getPageId());
			orangeLandingPage.setStatus(adLandingPage.getStatus());
			orangeLandingPage.setAdvertiserId(adLandingPage.getAdvertiserId());
			orangeLandingPage.setCreateTime(adLandingPage.getCreateTime());
			return orangeLandingPage;
		}
		return null;
	}
}
